from rest_framework import serializers
from django.forms import model_to_dict
from django.db.models import Max
import collections


from apps.publish.models import PublishModel,PublishImageModel
from apps.Detail.models import ViewerRecordModel,CommentRecordModel,FavorRecordModel

# 文章详情页序列化器
class PublishDetailModelSerializer(serializers.ModelSerializer):
    images = serializers.SerializerMethodField()
    createTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M")
    topic = serializers.SerializerMethodField()
    user = serializers.SerializerMethodField()
    viewr = serializers.SerializerMethodField()  # 访客记录
    comment = serializers.SerializerMethodField()  # 评论

    is_favor = serializers.SerializerMethodField()

    class Meta:
        model = PublishModel
        exclude = ["cover", ]

    def get_images(self, obj):
        images_queryset = PublishImageModel.objects.filter(article=obj)

        return [model_to_dict(i, fields=["id", "cos_path"]) for i in images_queryset]

    def get_topic(self, obj):
        return model_to_dict(obj.topic, fields=["id", "topic", "count"])

    def get_user(self, obj):
        return model_to_dict(obj.user, fields=["id", "nickName", "avatarUrl"])

    # 访客记录
    def get_viewr(self, obj):
        print(obj.id)
        queryset = ViewerRecordModel.objects.filter(article_id=obj.id)
        # print(queryset)
        viewr_object_list = queryset.order_by("-id")[0:10]

        context = {
            "count": queryset.count(),
            "result": [model_to_dict(i.user, fields=["nickName", "avatarUrl"]) for i in viewr_object_list]
        }

        return context

    def get_is_favor(self, obj):
        # 用户未登录
        user_object = self.context['request'].user
        if not user_object:
            return False
        # 用户已登录
        exists = FavorRecordModel.objects.filter(user=user_object,article=obj).exists()
        return exists


    # 评论功能
    def get_comment(self, obj):
        # 获取当前文章下的所有一级评论
        first_queryset = CommentRecordModel.objects.filter(article=obj,depth=1).order_by("-id").values(
            "id","content","depth","user__nickName","user__avatarUrl","createTime"
        )

        # 获取一级评论的id，用于索引一级评论下的评论
        first_id_list = [i['id'] for i in first_queryset]

        # 根据一级评论的id获取下一级的评论 且是最新的评论
        result = CommentRecordModel.objects.filter(article=obj,depth=2,reply_id__in=first_id_list).values(
            "reply_id").annotate(max_id=Max("id"))

        second_id_list = [i["max_id"] for i in result]

        # 获取二级评论
        second_queryset = CommentRecordModel.objects.filter(id__in=second_id_list).values(
            "id","content","depth","user__nickName",'user__avatarUrl',"createTime","reply_id","reply__user__nickName",
        )
        print(f"second_queryset:{second_queryset}")

        # 将一级评论 和 一级评论以下的评论 整合一起
        first_dict = collections.OrderedDict() #有序字典

        for i in first_queryset:
            i["createTime"] = i["createTime"].strftime("%Y-%m-%d %H:%M")
            first_dict[i["id"]] = i
        print(f"first_dict:{first_dict}")

        for node in second_queryset:
            node["createTime"] = node["createTime"].strftime("%Y-%m-%d %H:%M")
            first_dict[node['reply_id']]['child'] = [node,]
        print(f"first_dict:{first_dict}")

        return first_dict.values()


# 评论序列化器
class CommentModelSerializer(serializers.ModelSerializer):
    # source 字段反向查询
    user__nickName = serializers.CharField(source="user.nickName",label="评论者")
    user__avatarUrl = serializers.CharField(source="user.avatarUrl",label="评论者头像")
    createTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M",label="评论时间")
    reply_id = serializers.CharField(source="reply.id",label="回复评论的id")
    reply__user__nickName = serializers.CharField(source="reply.user.nickName",label="回复评论者的用户名")
    class Meta:
        model = CommentRecordModel
        exclude = ["article","user","reply","root"]



# 回复/发布评论序列化器
class CreateCommentModelSerializer(serializers.ModelSerializer):
    # read_only 不进行验证，但可以反序列化
    user__nickName = serializers.CharField(source="user.nickName",read_only=True)
    user__avatar = serializers.CharField(source="user.avatarUrl",read_only=True)
    createTime = serializers.DateTimeField(format="%Y-%m-%d %H:%M",read_only=True)
    reply_id = serializers.CharField(source="reply.id",read_only=True)
    reply__user__nickName = serializers.CharField(source="reply.user.nickName",read_only=True)
    class Meta:
        model = CommentRecordModel
        # fields = "__all__"
        exclude = ['user','favor_count']


# 点赞序列化器
class FavorModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = FavorRecordModel
        fields = ["article"]

